package org.example.common.filter;

import org.example.common.aspect.NotAuthUrlProperties;
import org.example.common.cache.LocalCache;
import org.example.common.config.ResultCode;
import org.example.common.ex.GateWayException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@Component
@EnableConfigurationProperties(value = NotAuthUrlProperties.class)
public class AuthorizationFilter implements Filter {
    /**
     * 不需要用户认证的URL
     */
    @Resource
    private NotAuthUrlProperties notAuthUrlProperties;
    @Resource
    private LocalCache<Map<String,String>> localCache;
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("=============");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("===2==========");
        HttpServletRequest req = (HttpServletRequest)request;
        String key = req.getHeader("key");
        String code = req.getHeader("code");
        if (!shouldSkip(req.getRequestURI())){
            //取参数
            Map<String,String> mm =localCache.getCache(key);
            if(ObjectUtils.isEmpty(mm)){
               // throw new GateWayException(ResultCode.AUTHORIZATION_HEADER_IS_EMPTY);
                throw new RuntimeException("测试全局异常处理中---没有权限");
            }else{
                String codeCach = mm.get("code");
                if(!codeCach.equals(code)){
                    throw new RuntimeException("测试全局异常处理中---没有权限");
                }
            }
        }
        chain.doFilter(request,response);
        System.out.println("==========666666=====");
    }

    @Override
    public void destroy() {
        System.out.println("=======4======");
    }
    /**
     * 方法实现说明:不需要授权的路径
     * @author:smlz
     * @param currentUrl 当前请求路径
     * @return:
     * @exception:
     * @date:2019/12/26 13:49
     */
    private boolean shouldSkip(String currentUrl) {
        //路径匹配器(简介SpringMvc拦截器的匹配器)
        //比如/oauth/** 可以匹配/oauth/token    /oauth/check_token等
        PathMatcher pathMatcher = new AntPathMatcher();
        for(String skipPath:notAuthUrlProperties.getShouldSkipUrls()) {
            if(pathMatcher.match(skipPath,currentUrl)) {
                return true;
            }
        }
        return false;
    }
}
